from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)

# MYSQL所在的主机名
host = '127.0.0.1'
# MYSQL监听的端口号
port = 3306
# 连接mysql时的用户名
username = 'root'
# 密码
password = 'root'
# mysql上创建的数据库名称
database = 'database_learn'

app.config['SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{username}:{password}@{host}:{port}" \
                                        f"/{database}?charset=utf8mb4"
db = SQLAlchemy(app)

migrate = Migrate(app,db)


class Person(db.Model):
    __tablename__="person"
    id =db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(100))
    signature = db.Column(db.String(100))

    def to_dict(self):
        return {
            'id':self.id,
            'name':self.name,
            'signature':self.signature
        }


class Hero(db.Model):
    __tablename__='hero'
    id=db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(100))
    carer = db.Column(db.String(100))

    def to_dict(self):
        return {
            'id':self.id,
            'name':self.name,
            'carer':self.carer
        }


class Play(db.Model):
    __tablename__ = 'play'
    person_id = db.Column(db.Integer, db.ForeignKey("person.id"),primary_key=True)
    hero_id = db.Column(db.Integer, db.ForeignKey("hero.id"),primary_key=True)

    def to_dict(self):
        return {
            "person_id": self.person_id,
            "hero_id": self.hero_id
        }


@app.route("/hero/add")
def add_hero():
    hero = Hero(name='诺克萨斯之手德莱厄斯',carer='战士')
    db.session.add(hero)
    db.session.commit()

    return "添加成功"


@app.route("/")
def hello():
    return "您好"


@app.route("/hero")
def hero():
    hero_list = Hero.query.all()
    data=[]
    for hero in hero_list:
        data.append(hero.to_dict())
    return data


if __name__ == '__main__':
    app.run()